package com.zed.app.push;

import java.io.InputStream;

import com.dbay.apns4j.IApnsService;
import com.dbay.apns4j.demo.Apns4jDemo;
import com.dbay.apns4j.impl.ApnsServiceImpl;
import com.dbay.apns4j.model.ApnsConfig;
import com.dbay.apns4j.model.Payload;

public class Apns4j {
	private static IApnsService apnsService;
	
	private static IApnsService getApnsService() {
		if (apnsService == null) {
			synchronized (Apns4j.class) {
				if(apnsService  == null){
					ApnsConfig config = new ApnsConfig();
					boolean dev = SystemConfig.getBoolean("remote.push.ios.dev");
					String profile = SystemConfig.getString("remote.push.ios.pro.profile");
					if(dev){
						profile = SystemConfig.getString("remote.push.ios.dev.profile");
					}
					InputStream is = Apns4jDemo.class.getClassLoader().getResourceAsStream(profile);
					config.setKeyStore(is);
					config.setDevEnv(dev);
					config.setPassword(SystemConfig.getString("remote.push.ios.password"));
					config.setPoolSize(3);
					config.setTimeout(0);//永远有效
					// 假如需要在同个java进程里给不同APP发送通知，那就需要设置为不同的name
					config.setName(SystemConfig.getString("remote.push.ios.name"));
					apnsService = ApnsServiceImpl.createInstance(config);
				}
			}
			
		}
		return apnsService;
	}
	
	/**
	 * 发送push消息
	 * @param token
	 * @param payload
	 */
	public static void pushMsg(String token,String json,String body,int badge,boolean isSound){
		Payload payload = new Payload();
		if (isSound){
			payload.setSound("messenger.aiff");
		}else{
			payload.setSound("Silence.aiff");
		}
		payload.setAlert(body);
		payload.setBadge(badge);
		payload.addParam("comments", json);
		getApnsService().sendNotification(token, payload);
	}
	
}
